<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <Header />
    
    <!-- 步骤指示器 -->
    <StepIndicator :current-step="currentStep" />
    
    <!-- 步骤1: 基本信息 -->
    <Step1BasicInfo 
      v-if="currentStep === 1"
      v-model="formData"
      @update:modelValue="updateFormData"
      @next="goToStep(2)"
    />
    
    <!-- 步骤2: 选择一级科室 -->
    <Step2PrimaryDept 
      v-if="currentStep === 2"
      v-model="formData"
      @update:modelValue="updateFormData"
      @previous="goToStep(1)"
      @next="goToStep(3)"
    />
    
    <!-- 步骤3: 选择二级科室 -->
    <Step3SecondaryDept 
      v-if="currentStep === 3"
      v-model="formData"
      :primary-departments="primaryDepartments"
      :secondary-departments="secondaryDepartments"
      :loading="loadingSecondaryDepartments"
      @update:modelValue="updateFormData"
      @previous="goToStep(2)"
      @next="handleStep3Submit"
      @load-secondary-departments="loadSecondaryDepartments"
    />
    
    <!-- 步骤4: 选择医生 -->
    <Step4Doctor 
      v-if="currentStep === 4"
      v-model="formData"
      :secondary-departments="secondaryDepartments"
      :doctors="doctors"
      :loading="loadingDoctors"
      @update:modelValue="updateFormData"
      @previous="goToStep(3)"
      @next="handleStep4Submit"
      @load-doctors="loadDoctors"
    />
    
    <!-- 步骤5: 选择预约时间 -->
    <Step5Time 
      v-if="currentStep === 5"
      v-model="formData"
      :doctors="doctors"
      :available-dates="availableDates"
      :available-periods="availablePeriods"
      :loading="loadingAvailableDates"
      @update:modelValue="updateFormData"
      @previous="goToStep(4)"
      @next="handleStep5Submit"
      @load-schedule="loadSchedule"
      @load-periods="loadPeriods"
    />
    
    <!-- 步骤6: 确认信息与提交 -->
    <Step6Confirmation 
      v-if="currentStep === 6"
      v-model="formData"
      :primary-departments="primaryDepartments"
      :secondary-departments="secondaryDepartments"
      :doctors="doctors"
      :questionnaire-status="getQuestionnaireStatus()"
      @previous="goToStep(5)"
      @submit="submitAppointment"
    />
    
    <!-- 问卷填写弹窗 -->
    <QuestionnaireModal
      :visible="showQuestionnaire"
      :department="selectedDepartment"
      :doctor="selectedDoctorName"
      :questions="questionnaire"
      v-model="questionnaireAnswers"
      @close="showQuestionnaire = false"
      @submit="submitQuestionnaire"
      @skip="skipQuestionnaire"
    />
    
    <!-- 跳过问卷确认弹窗 -->
    <SkipQuestionnaireModal
      :visible="showSkipConfirm"
      @confirm="confirmSkip"
      @cancel="cancelSkip"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import  request  from '@/utils/request'
import Header from './components/Header.vue'
import StepIndicator from './components/StepIndicator.vue'
import Step1BasicInfo from './components/Step1BasicInfo.vue'
import Step2PrimaryDept from './components/Step2PrimaryDept.vue'
import Step3SecondaryDept from './components/Step3SecondaryDept.vue'
import Step4Doctor from './components/Step4Doctor.vue'
import Step5Time from './components/Step5Time.vue'
import Step6Confirmation from './components/Step6Confirmation.vue'
import QuestionnaireModal from './components/QuestionnaireModal.vue'
import SkipQuestionnaireModal from './components/SkipQuestionnaireModal.vue'

const router = useRouter()

// 一、响应式数据
const currentStep = ref(1)
const showQuestionnaire = ref(false)
const showSkipConfirm = ref(false)
const loadingSecondaryDepartments = ref(false)
const loadingDoctors = ref(false)
const loadingAvailableDates = ref(false)
const selectedDepartment = ref('')
const selectedDoctorName = ref('')
const questionnaireAnswers = ref([]) // 存储问卷答案（按题目顺序）
const questionnaireLoading = ref(false)

// 问卷记录
const questionnaireRecord = ref({
  status: 'unhandled', // unhandled/answered/skipped
  answers: [],         // 存储用户答案数组
  doctorId: '',
  department: ''
})

// 表单数据
const formData = ref({
  name: '',
  idCard: '',
  phone: '',
  primaryDepartmentId: null,
  secondaryDepartmentId: null,
  doctorId: null,
  appointmentDate: null,
  appointmentPeriod: null,
  departments_id: '',
})

// 二、基础数据定义
const primaryDepartments = ref([
  { id: 1, name: '内科', icon: 'fas fa-stethoscope', description: '涵盖呼吸、消化、心血管等内科疾病诊疗' },
  { id: 2, name: '外科', icon: 'fas fa-syringe', description: '开展各类外科手术及外科疾病治疗' },
  { id: 3, name: '妇产科', icon: 'fas fa-baby-carriage', description: '妇科疾病诊治及产科孕产全程服务' },
  { id: 4, name: '男科', icon: 'fas fa-user-md', description: '男性生殖系统及相关疾病诊疗' },
  { id: 5, name: '儿科', icon: 'fas fa-child', description: '针对儿童各系统疾病的专业诊疗' },
  { id: 6, name: '五官科', icon: 'fas fa-eye', description: '眼、耳、鼻、喉及口腔疾病综合诊疗' },
  { id: 7, name: '肿瘤科', icon: 'fas fa-heartbeat', description: '肿瘤预防、诊断及综合治疗' },
  { id: 8, name: '皮肤性病科', icon: 'fas fa-allergies', description: '皮肤病与性传播疾病诊治' },
  { id: 9, name: '中医科', icon: 'fas fa-leaf', description: '中医辨证施治及传统疗法干预' },
  { id: 10, name: '传染科', icon: 'fas fa-shield-virus', description: '各类传染性疾病的诊治与防控' },
  { id: 11, name: '精神心理科', icon: 'fas fa-brain', description: '精神心理疾病诊疗与心理干预' }
])

// 动态数据
const secondaryDepartments = ref([])
const doctors = ref([])
const availableDates = ref([])
const availablePeriods = ref({ morning: true, afternoon: true })
const questionnaire = ref([]) // 问卷题目列表

// 三、计算属性
const selectedPrimaryDepartment = computed(() => {
  return primaryDepartments.value.find(d => d.id === formData.value.primaryDepartmentId) || {}
})

const selectedSecondaryDepartment = computed(() => {
  return secondaryDepartments.value.find(d => d.id === formData.value.secondaryDepartmentId) || {}
})

const selectedDoctor = computed(() => {
  return doctors.value.find(d => d.id === formData.value.doctorId) || {}
})

// 问卷是否全部填写
const isQuestionnaireFilled = computed(() => {
  return questionnaireAnswers.value.every(ans => ans && ans.trim() !== '')
})

// 四、核心流程方法
// 1. 页面跳转
const goToStep = (step) => {
  currentStep.value = step
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 更新表单数据
const updateFormData = (newData) => {
  formData.value = { ...formData.value, ...newData }
}

// 获取问卷状态文本
const getQuestionnaireStatus = () => {
  if (showSkipConfirm.value || questionnaireRecord.value.status !== 'answered') {
    return '未填写'
  }
  return '已填写'
}

// 2. 步骤1提交（基本信息校验）
const handleStep1Submit = () => {
  if (!formData.value.name.trim()) {
    alert('请输入姓名')
    return
  }
  if (!/^\d{18}$/.test(formData.value.idCard)) {
    alert('请输入有效的18位身份证号')
    return
  }
  if (!/^\d{11}$/.test(formData.value.phone)) {
    alert('请输入有效的11位手机号')
    return
  }
  goToStep(2)
}

// 3. 选择一级科室（加载二级科室）
const selectPrimaryDepartment = async (departmentId) => {
  formData.value.primaryDepartmentId = departmentId
  formData.value.secondaryDepartmentId = null
  formData.value.doctorId = null
  formData.value.appointmentDate = null
  formData.value.appointmentPeriod = null
  questionnaireRecord.value = { status: 'unhandled', answers: [], doctorId: '', department: '' }
  questionnaire.value = []
  questionnaireAnswers.value = []

  loadingSecondaryDepartments.value = true
  try {
    const primaryDeptName = selectedPrimaryDepartment.value.name
    const response = await request({
      url: `/system/department/sub-list?degree=${encodeURIComponent(primaryDeptName)}`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取二级科室失败')
    secondaryDepartments.value = response.data.map((item, index) => ({
      id: `${departmentId}${(index + 1).toString().padStart(2, '0')}`,
      originId: item.id,
      name: item.department,
      icon: item.icon || 'fas fa-stethoscope',
      description: item.description || '暂无描述'
    }))
  } catch (error) {
    console.error('获取二级科室失败:', error)
    alert(`获取二级科室失败：${error.message}`)
  } finally {
    loadingSecondaryDepartments.value = false
  }
}

// 加载二级科室（供子组件调用）
const loadSecondaryDepartments = async (primaryDepartmentId) => {
  formData.value.primaryDepartmentId = primaryDepartmentId
  formData.value.secondaryDepartmentId = null
  formData.value.doctorId = null
  formData.value.appointmentDate = null
  formData.value.appointmentPeriod = null
  questionnaireRecord.value = { status: 'unhandled', answers: [], doctorId: '', department: '' }
  questionnaire.value = []
  questionnaireAnswers.value = []

  loadingSecondaryDepartments.value = true
  try {
    const primaryDept = primaryDepartments.value.find(d => d.id === primaryDepartmentId)
    if (!primaryDept) return

    const primaryDeptName = primaryDept.name
    const response = await request({
      url: `/system/department/sub-list?degree=${encodeURIComponent(primaryDeptName)}`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取二级科室失败')
    secondaryDepartments.value = response.data.map((item, index) => ({
      id: `${primaryDepartmentId}${(index + 1).toString().padStart(2, '0')}`,
      originId: item.id,
      name: item.department,
      icon: item.icon || 'fas fa-stethoscope',
      description: item.description || '暂无描述'
    }))
  } catch (error) {
    console.error('获取二级科室失败:', error)
    alert(`获取二级科室失败：${error.message}`)
    secondaryDepartments.value = []
  } finally {
    loadingSecondaryDepartments.value = false
  }
}

// 4. 选择二级科室
const selectSecondaryDepartment = (departmentId) => {
  formData.value.secondaryDepartmentId = departmentId
  formData.value.doctorId = null
  formData.value.appointmentDate = null
  formData.value.appointmentPeriod = null
  questionnaireRecord.value = {
    status: 'unhandled',
    answers: [],
    doctorId: '',
    department: selectedSecondaryDepartment.value.name
  }
  doctors.value = []
}

// 5. 步骤3提交（加载医生列表）
const handleStep3Submit = async () => {
  if (!formData.value.secondaryDepartmentId) {
    alert('请先选择二级科室！')
    return
  }

  loadingDoctors.value = true
  try {
    const secondaryDeptName = selectedSecondaryDepartment.value.name
    const response = await request({
      url: `/system/doctor/dept/${encodeURIComponent(secondaryDeptName)}`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取医生列表失败')
    doctors.value = response.data.map(item => ({
      id: item.id,
      name: item.doctor,
      title: item.title || '医师',
      specialty: item.specialty || '暂无专长描述'
    }))
    if (doctors.value.length === 0) {
      alert('该二级科室暂无医生出诊，请选择其他科室')
      return
    }
    goToStep(4)
  } catch (error) {
    console.error('获取医生列表失败:', error)
    alert(`获取医生失败：${error.message}`)
  } finally {
    loadingDoctors.value = false
  }
}

// 加载医生列表（供子组件调用）
const loadDoctors = async (secondaryDepartmentId) => {
  const secondaryDept = secondaryDepartments.value.find(d => d.id === secondaryDepartmentId)
  if (!secondaryDept) return

  loadingDoctors.value = true
  try {
    const secondaryDeptName = secondaryDept.name
    const response = await request({
      url: `/system/doctor/dept/${encodeURIComponent(secondaryDeptName)}`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取医生列表失败')
    doctors.value = response.data.map(item => ({
      id: item.id,
      name: item.doctor,
      title: item.title || '医师',
      specialty: item.specialty || '暂无专长描述'
    }))
  } catch (error) {
    console.error('获取医生列表失败:', error)
    alert(`获取医生失败：${error.message}`)
    doctors.value = []
  } finally {
    loadingDoctors.value = false
  }
}

// 6. 选择医生
const selectDoctor = (doctorId) => {
  formData.value.doctorId = doctorId
  formData.value.appointmentDate = null
  formData.value.appointmentPeriod = null
  availableDates.value = []
  availablePeriods.value = { morning: true, afternoon: true }
  selectedDoctorName.value = selectedDoctor.value.name || ''
}

// 7. 步骤4提交（加载排班）
const handleStep4Submit = async () => {
  const doctor = selectedDoctor.value
  if (!doctor.id) {
    alert('请先选择医生！')
    return
  }

  selectedDepartment.value = selectedSecondaryDepartment.value.name
  selectedDoctorName.value = doctor.name
  questionnaireRecord.value.doctorId = doctor.id
  questionnaireRecord.value.department = selectedDepartment.value

  loadingAvailableDates.value = true
  try {
    const response = await request({
      url: `/system/doctor/schedule?doctorId=${doctor.id}&days=7`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取医生排班失败')
    availableDates.value = response.data
      .filter(item => item.available)
      .map(item => ({
        date: item.date,
        day: getWeekDay(item.date),
        month: item.date.split('-')[1],
        available: item.available
      }))

    if (availableDates.value.length === 0) {
      alert('该医生未来7天暂无排班，请选择其他医生')
      return
    }
    goToStep(5)
  } catch (error) {
    console.error('获取医生排班失败:', error)
    alert(`获取排班失败：${error.message}`)
  } finally {
    loadingAvailableDates.value = false
  }
}

// 加载医生排班（供子组件调用）
const loadSchedule = async (doctorId) => {
  const doctor = doctors.value.find(d => d.id === doctorId)
  if (!doctor) return

  loadingAvailableDates.value = true
  try {
    const response = await request({
      url: `/system/doctor/schedule?doctorId=${doctor.id}&days=7`,
      method: 'GET'
    })

    if (response.code !== 200) throw new Error(response.msg || '获取医生排班失败')
    availableDates.value = response.data
      .filter(item => item.available)
      .map(item => ({
        date: item.date,
        day: getWeekDay(item.date),
        month: item.date.split('-')[1],
        available: item.available
      }))
  } catch (error) {
    console.error('获取医生排班失败:', error)
    alert(`获取排班失败：${error.message}`)
    availableDates.value = []
  } finally {
    loadingAvailableDates.value = false
  }
}

// 8. 选择日期（加载可用时段）
const selectDate = async (date) => {
  formData.value.appointmentDate = date
  formData.value.appointmentPeriod = null

  try {
    const response = await request({
      url: `/system/doctor/schedule/period?doctorId=${formData.value.doctorId}&date=${encodeURIComponent(date)}`,
      method: 'GET'
    })

    if (response.code === 200) {
      availablePeriods.value = {
        morning: response.data.morning || false,
        afternoon: response.data.afternoon || false
      }
    } else {
      throw new Error(response.msg)
    }
  } catch (error) {
    console.error('获取时段失败:', error)
    alert(`获取时段失败：${error.message}`)
    availablePeriods.value = { morning: true, afternoon: true }
  }
}

// 加载可用时段（供子组件调用）
const loadPeriods = async (date) => {
  try {
    const response = await request({
      url: `/system/doctor/schedule/period?doctorId=${formData.value.doctorId}&date=${encodeURIComponent(date)}`,
      method: 'GET'
    })

    if (response.code === 200) {
      availablePeriods.value = {
        morning: response.data.morning || false,
        afternoon: response.data.afternoon || false
      }
    } else {
      throw new Error(response.msg)
    }
  } catch (error) {
    console.error('获取时段失败:', error)
    alert(`获取时段失败：${error.message}`)
    availablePeriods.value = { morning: true, afternoon: true }
  }
}

// 9. 选择时段
const selectPeriod = (period) => {
  formData.value.appointmentPeriod = period
}

// 10. 步骤5提交（打开问卷）
const handleStep5Submit = () => {
  if (!formData.value.appointmentDate || !formData.value.appointmentPeriod) {
    alert('请选择完整的预约时间！')
    return
  }
  openQuestionnaire()
}

// 五、问卷相关方法
// 打开问卷（加载题目）
const openQuestionnaire = async () => {
  questionnaireLoading.value = true
  await fetchQuestionnaire()
  showQuestionnaire.value = true
  questionnaireLoading.value = false
}

// 加载问卷数据
const fetchQuestionnaire = async () => {
  try {
    const res = await request({
      url: '/system/questionnaire/by-department',
      method: 'GET',
      params: { department: selectedDepartment.value }
    })

    if (res.code !== 200) throw new Error(res.msg || '加载问卷失败')
    if (res.data && res.data.length > 0) {
      // 限制问卷题目数量不超过10题（匹配表结构的answer1-answer10）
      questionnaire.value = res.data.slice(0, 10)
    } else {
      alert('该科室暂无定制问卷，将显示通用健康问卷（最多10题）')
      questionnaire.value = [
        { text: '您是否有以下症状？', options: ['无', '腹痛', '腹胀', '恶心', '呕吐', '反酸'] },
        { text: '症状持续了多长时间？', options: ['1周以内', '1-2周', '2-4周', '1-3个月', '3个月以上'] },
        { text: '症状发作的频率？', options: ['偶尔', '每天1次', '每天多次', '每周几次'] },
        { text: '是否有以下病史？', options: ['无', '胃溃疡', '胃炎', '肠炎', '肝炎', '其他'] },
        { text: '是否服用过相关药物？', options: ['否', '是，但效果不佳', '是，效果良好'] }
      ].slice(0, 10) // 确保不超过10题
    }

    // 初始化答案数组（与题目数量一致）
    questionnaireAnswers.value = questionnaire.value.map(() => '')
    // 恢复历史回答（如果有）
    if (questionnaireRecord.value.status === 'answered' && questionnaireRecord.value.answers.length === questionnaire.value.length) {
      questionnaireAnswers.value = [...questionnaireRecord.value.answers]
    }
  } catch (error) {
    console.error('加载问卷失败', error)
    alert(`问卷加载失败：${error.message}，将显示通用健康问卷`)
    questionnaire.value = [
      { text: '您是否有以下症状？', options: ['无', '腹痛', '腹胀', '恶心', '呕吐', '反酸'] },
      { text: '症状持续了多长时间？', options: ['1周以内', '1-2周', '2-4周', '1-3个月', '3个月以上'] },
      { text: '症状发作的频率？', options: ['偶尔', '每天1次', '每天多次', '每周几次'] },
      { text: '是否有以下病史？', options: ['无', '胃溃疡', '胃炎', '肠炎', '肝炎', '其他'] },
      { text: '是否服用过相关药物？', options: ['否', '是，但效果不佳', '是，效果良好'] }
    ].slice(0, 10)
    questionnaireAnswers.value = questionnaire.value.map(() => '')
  }
}

// 提交问卷
const submitQuestionnaire = () => {
  if (!isQuestionnaireFilled.value) {
    alert('请完成所有问题后再提交！')
    return
  }
  questionnaireRecord.value.status = 'answered'
  questionnaireRecord.value.answers = [...questionnaireAnswers.value]
  showQuestionnaire.value = false
  goToStep(6)
}

// 跳过问卷
const skipQuestionnaire = () => {
  showSkipConfirm.value = true
}

const confirmSkip = () => {
  questionnaireRecord.value.status = 'skipped'
  questionnaireRecord.value.answers = [] // 跳过则答案为空
  showSkipConfirm.value = false
  showQuestionnaire.value = false
  goToStep(6)
}

const cancelSkip = () => {
  showSkipConfirm.value = false
}

// 六、Token 处理（核心修复：从 localStorage 提取，适配登录响应体存储）
// 提取 Token：从 localStorage 读取（登录时已存储）
const getTokenFromCookie = () => {
  const cookies = document.cookie.split('; ');
  for (const cookie of cookies) {
    const [name, value] = cookie.split('=');
    if (name === 'Admin-Token') { // 精确匹配Cookie名称
      return decodeURIComponent(value);
    }
  }
  return null;
};

// 七、预约提交（核心：按answer1-answer10映射答案 + 正确携带Token）
const submitAppointment = async () => {
  // 1. 前置校验
  if (!formData.value.name.trim()) { alert('请填写患者姓名！'); return; }
  if (!formData.value.idCard || !/^\d{17}[\dXx]$/.test(formData.value.idCard)) { alert('请填写有效的身份证号！'); return; }
  if (!formData.value.phone || !/^\d{11}$/.test(formData.value.phone)) { alert('请填写有效的手机号！'); return; }
  if (!formData.value.primaryDepartmentId) { alert('请选择一级科室！'); return; }
  if (!formData.value.secondaryDepartmentId) { alert('请选择二级科室！'); return; }
  if (!formData.value.doctorId || !selectedDoctorName.value) { alert('请选择就诊医生！'); return; }
  if (!formData.value.appointmentDate) { alert('请选择预约日期！'); return; }
  if (!formData.value.appointmentPeriod) { alert('请选择预约时段！'); return; }
  if (questionnaireRecord.value.status === 'unhandled') { alert('请完成或跳过问卷后再提交！'); return; }

    try {
      // 2. 提取Token（从Cookie中读取）
      const token = getTokenFromCookie();
      if (!token) {
        alert('登录态已失效，请重新登录！');
        window.location.href = '/login';
        return;
      }

    // 3. 构造提交数据（核心：映射answer1-answer10）
    const submitData = {
      name: formData.value.name.trim(),
      identity: formData.value.idCard.trim(),
      phone: formData.value.phone.trim(),
      departmentId: secondaryDepartments.value.find(dept => dept.id === formData.value.secondaryDepartmentId)?.originId || formData.value.secondaryDepartmentId,
      doctorId: `${formData.value.doctorId}`,
      doctor: selectedDoctorName.value.trim(),
      skipQuery: questionnaireRecord.value.status === 'skipped' ? 'true' : 'false',
      datetime: `${formData.value.appointmentDate} ${
        formData.value.appointmentPeriod === 'morning' ? '09:30:00' : '14:30:00'
      }`,
      appointmentDate: `${formData.value.appointmentDate}`,
      // 关键：按题目顺序映射到answer1-answer10，未使用的字段设为null
      ...questionnaireRecord.value.answers.reduce((acc, answer, index) => {
        const key = `answer${index + 1}`; // 第1题→answer1，第2题→answer2...
        acc[key] = answer.trim() || null; // 空答案设为null
        return acc;
      }, {}),
      // 填充剩余未使用的answerX字段（如问卷5题，则answer6-answer10设为null）
      ...Array.from({ length: 10 - questionnaireRecord.value.answers.length }, (_, i) => {
        const key = `answer${questionnaireRecord.value.answers.length + 1 + i}`;
        return { [key]: null };
      }).reduce((acc, item) => ({ ...acc, ...item }), {})
    };

    // 4. 发送请求（携带 Token 到请求头）
    const response = await request({
      url: '/reservation/submit',
      method: 'POST',
      data: submitData
    });

    // 5. 响应处理
    if (response.code !== 200) {
      throw new Error(response.msg || '预约提交失败');
    }

    // 6. 提交成功
    const appointmentId = response.data || '未知';
    saveAppointmentHistory(appointmentId);
    alert(`🎉 预约成功！\n预约号:${appointmentId}\n请凭身份证在预约时间到院就诊`);
    resetForm();
    goToStep(1);

  } catch (error) {
    console.error('提交预约失败:', error);
    alert(`❌ 预约失败：${error.message}`);
  }
};

// 八、辅助方法
// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return isNaN(date.getTime()) ? '' : `${date.getFullYear()}年${(date.getMonth() + 1)}月${date.getDate()}日`;
};

// 获取星期几
const getWeekDay = (dateString) => {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return days[new Date(dateString).getDay()];
};

// 保存预约历史
const saveAppointmentHistory = (appointmentId) => {
  if (!appointmentId || appointmentId === '未知') return;
  try {
    const history = JSON.parse(localStorage.getItem('appointmentHistory') || '[]');
    const filteredHistory = history.filter(item => item.appointmentId !== appointmentId);
    filteredHistory.unshift({
      appointmentId,
      name: formData.value.name.trim(),
      idCard: formData.value.idCard.trim().replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3'),
      phone: formData.value.phone.trim().replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3'),
      department: selectedSecondaryDepartment.value.name || '未知科室',
      doctor: selectedDoctorName.value.trim(),
      appointmentDate: formatDate(formData.value.appointmentDate),
      appointmentPeriod: formData.value.appointmentPeriod === 'morning' ? '上午' : '下午',
      submitTime: new Date().toLocaleString(),
      questionnaireStatus: questionnaireRecord.value.status === 'answered' ? '已填写' : '已跳过'
    });
    localStorage.setItem('appointmentHistory', JSON.stringify(filteredHistory.slice(0, 5)));
  } catch (e) {
    console.error('保存预约历史失败:', e);
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    idCard: '',
    phone: '',
    primaryDepartmentId: null,
    secondaryDepartmentId: null,
    doctorId: null,
    appointmentDate: null,
    appointmentPeriod: null,
  };
  questionnaire.value = [];
  questionnaireAnswers.value = [];
  questionnaireRecord.value = { status: 'unhandled', answers: [], doctorId: '', department: '' };
  showQuestionnaire.value = false;
  showSkipConfirm.value = false;
  selectedDepartment.value = '';
  selectedDoctorName.value = '';
  secondaryDepartments.value = [];
  doctors.value = [];
  availableDates.value = [];
  availablePeriods.value = { morning: true, afternoon: true };
  localStorage.removeItem('appointmentForm');
  localStorage.removeItem('questionnaireAnswers');
};

// 跳转我的预约
const goToManagement = () => {
  router.push('/reservation/Management');
};

// 九、生命周期钩子
onMounted(() => {
  // 恢复本地存储数据
  const savedForm = localStorage.getItem('appointmentForm');
  const savedAnswers = localStorage.getItem('questionnaireAnswers');
  if (savedForm) {
    try {
      formData.value = { ...formData.value, ...JSON.parse(savedForm) };
      if (formData.value.primaryDepartmentId) {
        selectPrimaryDepartment(formData.value.primaryDepartmentId);
      }
    } catch (e) {
      console.error('恢复表单数据失败:', e);
      localStorage.removeItem('appointmentForm');
    }
  }
  if (savedAnswers) {
    try {
      questionnaireAnswers.value = JSON.parse(savedAnswers);
    } catch (e) {
      console.error('恢复问卷答案失败:', e);
      localStorage.removeItem('questionnaireAnswers');
    }
  }

  // 实时保存表单和问卷答案
  watch(formData, (newVal) => {
    localStorage.setItem('appointmentForm', JSON.stringify(newVal));
  }, { deep: true });

  watch(questionnaireAnswers, (newVal) => {
    localStorage.setItem('questionnaireAnswers', JSON.stringify(newVal));
  }, { deep: true });
});
</script>

<style scoped>
/* 原有的样式保持不变，只添加新的样式 */

.btn-management {
  display: inline-flex;
  align-items: center;
  padding: 12px 24px;
  font-size: 18px;
  font-weight: 600;
  background-color: #2ecc71;
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin-left:400px;
}

.btn-management:hover {
  background-color: #27ae60;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}

.btn-management i {
  margin-right: 8px;
}
/* 时间选择样式 */
.time-selection {
  margin-bottom: 20px;
}

.time-selection h3 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #333;
}

.dates-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
  margin-bottom: 30px;
}

.date-card {
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  padding: 15px 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.date-card:hover {
  border-color: var(--primary-light);
  transform: translateY(-2px);
}

.date-card.selected {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.1);
}

.date-day {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.date-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.date-month {
  font-size: 14px;
  color: #666;
}

.period-selection {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.period-card {
  display: flex;
  align-items: center;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.period-card:hover {
  border-color: var(--primary-light);
  transform: translateY(-2px);
}

.period-card.selected {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.1);
}

.period-icon {
  font-size: 32px;
  color: var(--primary-color);
  margin-right: 15px;
}

.period-info h4 {
  font-size: 20px;
  margin: 0 0 5px 0;
  color: #333;
}

.period-info p {
  font-size: 16px;
  color: #666;
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dates-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .period-selection {
    grid-template-columns: 1fr;
  }

  .btn-management {
      width: 100%;
      justify-content: center;
    }

}

@media (max-width: 480px) {
  .dates-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 原有的其他样式保持不变 */
:root {
  --primary-color: #3498db;
  --primary-light: #5dade2;
  --primary-dark: #2980b9;
  --secondary-color: #2ecc71;
  --secondary-light: #58d68d;
  --secondary-dark: #27ae60;
  --danger-color: #e74c3c;
  --warning-color: #f39c12;
  --light-bg: #f8f9fa;
  --card-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
  --card-shadow-hover: 0 10px 20px rgba(0, 0, 0, 0.15);
}

* {
  box-sizing: border-box;
}

body {
  background-color: #f5f7fa;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
  line-height: 1.6;
  font-size: 18px;
}

.app-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
  color: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 30px;
  box-shadow: var(--card-shadow);
}

.header-content {
  display: flex;
  align-items: center;
}

.hospital-icon {
  font-size: 42px;
  margin-right: 20px;
}

.header-text h1 {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.header-text p {
  font-size: 20px;
  margin: 0;
  opacity: 0.9;
}

/* 步骤指示器 */
.step-indicator {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
  position: relative;
}

.step-indicator::before {
  content: '';
  position: absolute;
  top: 30px;
  left: 0;
  right: 0;
  height: 4px;
  background-color: #e0e0e0;
  z-index: 1;
}

.step {
  text-align: center;
  z-index: 2;
  background-color: white;
  padding: 0 15px;
  flex: 1;
}

.step-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #e0e0e0;
  color: #777;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px;
  font-weight: bold;
  font-size: 24px;
  transition: all 0.3s ease;
  border: 4px solid white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.step.active .step-circle {
  background-color: var(--primary-color);
  color: white;
  transform: scale(1.1);
}

.step.completed .step-circle {
  background-color: var(--secondary-color);
  color: white;
}

.step-text {
  font-size: 18px;
  font-weight: 600;
}

/* 表单卡片 */
.form-card {
  background-color: white;
  border-radius: 16px;
  box-shadow: var(--card-shadow);
  padding: 30px;
  margin-bottom: 30px;
}

.form-title {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 20px;
}

.form-icon {
  font-size: 32px;
  color: var(--primary-color);
  margin-right: 15px;
}

.form-title h2 {
  font-size: 28px;
  font-weight: 700;
  color: var(--primary-dark);
  margin: 0;
}

.form-description {
  margin-bottom: 25px;
}

.form-description p {
  font-size: 20px;
  color: #555;
  margin: 0;
}

/* 表单组 */
.form-group {
  margin-bottom: 25px;
}

.form-label {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #444;
}

.form-label i {
  margin-right: 10px;
  color: var(--primary-color);
  width: 24px;
  text-align: center;
}

.form-control {
  width: 100%;
  padding: 16px 20px;
  font-size: 20px;
  border: 2px solid #ddd;
  border-radius: 10px;
  transition: all 0.3s;
}

.form-control:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

.form-control::placeholder {
  color: #aaa;
  font-size: 18px;
}

/* 按钮 */
.form-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px 30px;
  font-size: 20px;
  font-weight: 600;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 160px;
}

.btn i {
  margin: 0 8px;
}

.btn-primary {
  background-color: #e0e0e0;
  color: #555;
  border: 2px solid var(--primary-color) !important;
}

.btn-primary query{
    background-color: #e0e0e0;
    color: #555;
    border: 2px solid var(--primary-color) !important;
}

.btn-primary:hover {
  background-color: #e0e0e0;
  border-color: var(--primary-dark) !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.btn-primary:disabled {
  background-color: #bdc3c7 !important;
  border-color: #bdc3c7 !important;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-secondary {
  background-color: #e0e0e0;
  color: #555;
}

.btn-secondary:hover {
  background-color: #d0d0d0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.btn-secondary:disabled {
  background-color: #f0f0f0;
  color: #aaa;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 科室网格 */
.departments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.department-card {
  display: flex;
  align-items: center;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  background: white;
}

.department-card:hover {
  border-color: var(--primary-light);
  transform: translateY(-3px);
  box-shadow: var(--card-shadow-hover);
}

.department-card.selected {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.05);
}

.department-icon {
  font-size: 32px;
  color: var(--primary-color);
  margin-right: 15px;
  width: 50px;
  text-align: center;
}

.department-info h3 {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #333;
}

.department-info p {
  font-size: 18px;
  color: #666;
  margin: 0;
}

.checkmark {
  position: absolute;
  top: 15px;
  right: 15px;
  color: var(--secondary-color);
  font-size: 24px;
}

/* 医生列表 */
.doctors-list {
  margin-bottom: 20px;
}

.doctor-card {
  display: flex;
  align-items: center;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.doctor-card:hover {
  border-color: var(--primary-light);
  transform: translateY(-2px);
  box-shadow: var(--card-shadow);
}

.doctor-card.selected {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.05);
}

.doctor-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-light), var(--primary-dark));
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: white;
  font-size: 28px;
}

.doctor-info {
  flex: 1;
}

.doctor-info h3 {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 5px 0;
  color: #333;
}

.doctor-info .specialty {
  font-size: 18px;
  color: #555;
  margin: 0 0 5px 0;
}

.doctor-info .experience {
  font-size: 16px;
  color: #777;
  margin: 0;
}

.doctor-info .schedule {
  font-size: 14px;
  color: var(--primary-color);
  margin: 5px 0 0 0;
}

.doctor-selector {
  margin-left: 15px;
}

.radio-container {
  position: relative;
  width: 28px;
  height: 28px;
}

.radio-input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.radio-label {
  display: block;
  width: 28px;
  height: 28px;
  border: 2px solid #ddd;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.radio-input:checked + .radio-label {
  border-color: var(--primary-color);
  background-color: var(--primary-color);
}

.radio-input:checked + .radio-label::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 12px;
  height: 12px;
  background-color: white;
  border-radius: 50%;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-icon {
  font-size: 60px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 20px;
  color: #777;
}

/* 成功消息 */
.success-message {
  display: flex;
  align-items: center;
  background-color: rgba(46, 204, 113, 0.1);
  border: 2px solid var(--secondary-color);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  width: 900px;
  height: 100px;
}

.success-icon {
  font-size: 32px;
  color: var(--secondary-color);
  margin-right: 15px;
}

.success-message p {
  font-size: 20px;
  font-weight: 600;
  color: var(--secondary-dark);
  margin: 0;
}

/* 摘要卡片 */
.summary-card {
  background-color: #f8f9fa;
  border-radius: 12px;
  padding: 25px;
  margin-top: 20px;
}

.summary-card h3 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 20px 0;
  color: var(--primary-dark);
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 10px;
}

.summary-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.summary-label {
  display: flex;
  align-items: center;
  font-weight: 600;
  min-width: 180px;
  font-size: 18px;
  color: #555;
}

.summary-label i {
  margin-right: 10px;
  color: var(--primary-color);
  width: 20px;
  text-align: center;
}

.summary-value {
  font-size: 18px;
  color: #333;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
}

.questionnaire-modal {
  max-width: 700px;
}

.modal-header {
  display: flex;
  align-items: center;
  padding: 25px;
  border-bottom: 2px solid #f0f0f0;
  position: relative;
}

.modal-icon {
  font-size: 28px;
  color: var(--primary-color);
  margin-right: 15px;
}

.modal-title {
  font-size: 24px;
  font-weight: 700;
  color: var(--primary-dark);
  margin: 0;
  flex: 1;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #777;
  cursor: pointer;
  padding: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.btn-close:hover {
  color: #333;
  transform: scale(1.1);
}

.modal-body {
  padding: 25px;
}

.modal-description {
  font-size: 18px;
  color: #555;
  margin-bottom: 15px;
}

.modal-footer .btn {
  display: inline-flex !important;
  visibility: visible !important;
}

/* 问卷样式 */
.question-item {
  margin-bottom: 30px;
}

.question-text {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
}

.options-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  border-color: var(--primary-light);
  background-color: rgba(52, 152, 219, 0.05);
}

.option-item.selected {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.1);
}

.option-radio {
  width: 24px;
  height: 24px;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.option-item.selected .option-radio {
  border-color: var(--primary-color);
}

.radio-dot {
  width: 12px;
  height: 12px;
  background-color: var(--primary-color);
  border-radius: 50%;
}

.option-text {
  font-size: 18px;
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  body {
    font-size: 16px;
  }

  .app-container {
    padding: 15px;
  }

  .header {
    padding: 20px;
  }

  .header-content {
    flex-direction: column;
    text-align: center;
  }

  .hospital-icon {
    margin-right: 0;
    margin-bottom: 15px;
    font-size: 36px;
  }

  .header-text h1 {
    font-size: 26px;
  }

  .header-text p {
    font-size: 18px;
  }

  .step-indicator {
    flex-wrap: wrap;
  }

  .step {
    margin-bottom: 15px;
    flex: 0 0 33.33%;
  }

  .step-circle {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }

  .step-text {
    font-size: 16px;
  }

  .form-card {
    padding: 20px;
  }

  .form-title h2 {
    font-size: 24px;
  }

  .form-icon {
    font-size: 28px;
  }

  .form-label {
    font-size: 18px;
  }

  .form-control {
    font-size: 18px;
    padding: 14px 16px;
  }

  .btn {
    display: inline-flex !important;
    align-items: center;
    justify-content: center;
    padding: 16px 30px;
    font-size: 20px;
    font-weight: 600;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.3s;
    min-width: 160px;
    visibility: visible !important;
    opacity: 1 !important;
  }

  .departments-grid {
    grid-template-columns: 1fr;
  }

  .department-card {
    padding: 15px;
  }

  .department-info h3 {
    font-size: 20px;
  }

  .department-info p {
    font-size: 16px;
  }

  .doctor-card {
    padding: 15px;
  }

  .doctor-avatar {
    width: 60px;
    height: 60px;
    font-size: 24px;
    margin-right: 15px;
  }

  .doctor-info h3 {
    font-size: 20px;
  }

  .doctor-info .specialty {
    font-size: 16px;
  }

  .doctor-info .experience {
    font-size: 14px;
  }

  .modal-content {
    max-width: 100%;
  }

  .modal-title {
    font-size: 22px;
  }

  .modal-description {
    font-size: 16px;
  }

  .question-text {
    font-size: 18px;
  }

  .option-text {
    font-size: 16px;
  }

  .summary-label, .summary-value {
    font-size: 16px;
  }

  .form-buttons {
    flex-direction: column;
    gap: 15px;
  }

  .form-buttons .btn {
    width: 100%;
  }

  .success-message {
    width: 100%;
    height: auto;
    flex-direction: column;
    text-align: center;
  }
  .modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }
  .modal-container {
    width: 400px;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  .modal-header {
    margin-bottom: 15px;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }
  .modal-body {
    margin-bottom: 20px;
    color: #666;
  }
  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>
<style scoped>
/* 补充必要样式（可选，根据你的现有样式调整） */
.required { color: red; }
.highlight { color: #1890ff; font-weight: bold; }
.loading-state, .empty-state { text-align: center; padding: 40px 0; color: #666; }
.loading-state i { font-size: 40px; margin-bottom: 16px; color: #1890ff; }
.empty-state i { font-size: 40px; margin-bottom: 16px; color: #ccc; }
.doctor-title { font-size: 14px; color: #666; font-weight: normal; margin-left: 8px; }
.period-desc { font-size: 12px; color: #666; margin-top: 4px; }
.period-card.unavailable { opacity: 0.5; cursor: not-allowed; }
.date-card.unavailable { opacity: 0.5; cursor: not-allowed; }
.date-tag { position: absolute; bottom: 4px; right: 4px; background: #ff4d4f; color: white; font-size: 10px; padding: 2px 4px; border-radius: 2px; }
.questionnaire-entry { text-align: center; margin: 20px 0; }
</style>